<template>
  <div class="login-container">
    <div class="login-card">
      <h2 class="login-title">实验室环境监测系统</h2>
      <el-form ref="formRef" :model="form" :rules="rules" label-position="top" @keyup.enter="onSubmit">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="onSubmit" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  </template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const store = useStore()

const formRef = ref()
const submitting = ref(false)
const form = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const onSubmit = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    try {
      await store.dispatch('login', { username: form.username, password: form.password })
      ElMessage.success('登录成功')
      const redirect = route.query.redirect || '/data-statistics'
      router.replace(String(redirect))
    } catch (e) {
      ElMessage.error(e?.message || '登录失败')
    } finally {
      submitting.value = false
    }
  })
}
</script>

<style>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}
.login-card {
  width: 360px;
  padding: 28px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 8px 24px rgba(0,0,0,0.08);
}
.login-title {
  text-align: center;
  margin: 0 0 16px 0;
}
</style>


